<template>
	<div class="lc_wrap">
		<el-row class="proportion">
			<el-col :span="leftWidth">
				<div class="box treeBox">
					<basic-container>
						<lcTree @ready="ready" :deviceType='deviceType'></lcTree>
					</basic-container>
				</div>
			</el-col>
			<el-col :span="rightWidth" class="table-wrapper">
				<overlay @changeTreeBox="changeTreeBox"></overlay>
				<basic-container>
					<div class="search-tools">
						<div class="search-left">
							<div>
								<!-- 环比日 -->
								<div v-if="dateType==2&&propId==2">
									<el-date-picker v-model="newDataTime1" type="date" size="small" value-format="yyyy-MM-dd" :picker-options="pickerOption" placeholder="选择日期" :clearable='false' style="margin-right:20px;" @change="changNewDataTime1"></el-date-picker>
									<el-date-picker v-model="newDataTime2" type="date" size="small" value-format="yyyy-MM-dd" :picker-options="pickerOption" placeholder="选择日期" :clearable='false' @change="changNewDataTime2"></el-date-picker>
								</div>

								<!-- 环比月 -->
								<div v-if="dateType==4&&propId==2">
									<el-date-picker v-model="newDataTime3" type="month" size="small" value-format="yyyy-MM" :picker-options="pickerOption" placeholder="选择日期" :clearable='false' style="margin-right:20px;" @change="changNewDataTime3"></el-date-picker>
									<el-date-picker v-model="newDataTime4" type="month" size="small" value-format="yyyy-MM" :picker-options="pickerOption" placeholder="选择日期" :clearable='false' @change="changNewDataTime4"></el-date-picker>
								</div>

								<!-- 同比日 -->
								<div v-if="dateType==2&&propId==1">
									<el-date-picker v-model="newDataTime5" type="date" size="small" value-format="yyyy-MM-dd" :picker-options="pickerOption" placeholder="选择日期" :clearable='false' style="margin-right:20px;"></el-date-picker>
								</div>

								<!-- 同比月 -->
								<div v-if="dateType==4&&propId==1">
									<el-date-picker v-model="newDataTime6" type="month" size="small" value-format="yyyy-MM" :picker-options="pickerOption" placeholder="选择日期" :clearable='false' style="margin-right:20px;"></el-date-picker>
								</div>

							</div>

							<div style="margin-left:20px;">
								<el-select size="small" v-model="gene">
									<el-option v-for="(item, index) in geneList" :key="index" :label="item.alias" :value="item.factorCode"></el-option>
								</el-select>
							</div>

							<div style="margin-left:20px;">
								<el-select size="small" v-model="propId">
									<el-option v-for="(item, index) in propList" :key="index" :label="item.name" :value="item.id"></el-option>
								</el-select>
							</div>
						</div>

						<div class="search-right">
							<div class="search-tabs">
								<el-radio v-model="dateType" v-for="(item, index) in dateTypeList" :key="index" :label="item.label" :disabled="item.disable">{{ item.value }}
								</el-radio>
							</div>
							<div class="searcg-btns">
								<el-button type="primary" size="small" icon="el-icon-search" @click="search">搜 索</el-button>
							</div>
						</div>
					</div>
					<e-chart autoresize :options="chartOptions" style="height:45%;" ref="charts" id="charts"></e-chart>
					<e-chart autoresize :options="barChartOptions" style="height:45%;"></e-chart>
				</basic-container>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import { getDeptTree, getTypes, getLine, getFactorList, getBar } from "@/api/airq/proportion";
	import { mapGetters } from "vuex";
	import { dateFormat, getPreMonth, getNextMonth, getPreYear, getPreYear2 } from "@/util/date";
	import lcTree from "@/components/common/tree.vue";
	import overlay from "@/components/common/overlay.vue";
	export default {
		components: {
			lcTree,
			overlay
		},
		data() {
			let _this = this
			return {
				newDataTime1: '', // 绑定环比（日）的起始时间控件
				newDataTime2: '', // 绑定环比（日）的截止时间控件
				newDataTime3: '', // 绑定环比（月）的起始时间控件
				newDataTime4: '', // 绑定环比（月）的截止时间控件
				newDataTime5: '', // 绑定同比（日）的时间控件
				newDataTime6: '', // 绑定同比（月）的时间控件
				chartOptions: {},
				barChartOptions: {}, //柱状图
				leftWidth: this.$leftWidth,
				rightWidth: this.$rightWidth,
				loading: false,
				data: [],
				// 左侧树配置属性
				treeOption: {
					nodeKey: 'id',
					addBtn: false,
					menu: false,
					size: 'small',
					defaultExpandAll: true,
					props: {
						label: 'title',
						value: 'value',
						children: 'children'
					}
				},
				treeData: [],
				nodeId: null,
				deptInfoName: '',
				deptInfoId: '',
				dateType: 2, // 日期格式：日、月、年
				dateTime: '', // 默认显示的日期
				dateTime2: dateFormat(new Date(), 'yyyy-MM-dd'), // 默认显示的日期
				dateTypeList: [{
						label: 2,
						value: '日'
					},
					{
						label: 4,
						value: '月'
					}
				],
				pickerOption: {
					firstDayOfWeek: 1,
					disabledDate(time) {
						return _this.dateType == 3 ? false : time.getTime() > Date.now()
					},
				},
				geneList: [],
				gene: '',
				unit: '',
				propList: [{
					name: '环比',
					id: 2
				}, {
					name: '同比',
					id: 1
				}],
				propId: 2,
				interval: 59,
			};
		},
		computed: {
			...mapGetters(["permission"]),
		},
		mounted() {
			// 初始化时间
			let myDate = new Date()
			myDate.setTime(myDate.getTime() - 24 * 60 * 60 * 1000);
			this.newDataTime1 = dateFormat(new Date(myDate), 'yyyy-MM-dd')
			this.newDataTime2 = dateFormat(new Date, 'yyyy-MM-dd')
			// this.initData()
		},
		watch: {
			propId(val) {
				if(this.dateType == 2 && val == 2) {
					let myDate = new Date()
					myDate.setTime(myDate.getTime() - 24 * 60 * 60 * 1000);
					this.newDataTime1 = dateFormat(new Date(myDate), 'yyyy-MM-dd')
					this.newDataTime2 = dateFormat(new Date, 'yyyy-MM-dd')
				} else if(this.dateType == 4 && val == 2) {
					this.newDataTime3 = getPreMonth(dateFormat(new Date, 'yyyy-MM-dd')).slice(0, 7)
					this.newDataTime4 = dateFormat(new Date, 'yyyy-MM-dd').slice(0, 7)
				} else if(this.dateType == 2 && val == 1) {
					this.newDataTime5 = dateFormat(new Date, 'yyyy-MM-dd')
				} else if(this.dateType == 4 && val == 1) {
					this.newDataTime6 = dateFormat(new Date, 'yyyy-MM-dd').slice(0, 7)
				}
			},
			dateType(val) {
				if(val == 2 && this.propId == 2) {
					this.interval = 59
					let myDate = new Date()
					myDate.setTime(myDate.getTime() - 24 * 60 * 60 * 1000);
					this.newDataTime1 = dateFormat(new Date(myDate), 'yyyy-MM-dd')
					this.newDataTime2 = dateFormat(new Date, 'yyyy-MM-dd')
				} else if(val == 4 && this.propId == 2) {
					this.interval = 0
					this.newDataTime3 = getPreMonth(dateFormat(new Date, 'yyyy-MM-dd')).slice(0, 7)
					this.newDataTime4 = dateFormat(new Date, 'yyyy-MM-dd').slice(0, 7)
				} else if(val == 2 && this.propId == 1) {
					this.interval = 59
					this.newDataTime5 = dateFormat(new Date, 'yyyy-MM-dd')
				} else if(val == 4 && this.propId == 1) {
					this.interval = 0
					this.newDataTime6 = dateFormat(new Date, 'yyyy-MM-dd').slice(0, 7)
				}
				return false
				this.getTimeProp()
			},
		},
		methods: {
			async ready(data) {
				// this.nodeId = data.key
				// this.deptInfoName = data.title
				// this.deptInfoId = data.key
				// this.onLoad()
				//
				this.nodeId = data.key
				this.deptInfoName = data.title
				this.deptInfoId = data.key
				await getFactorList(this.nodeId).then(res => {
					this.geneList = res.data.data;
					this.gene = this.geneList[0].factorCode;
					this.unit = this.geneList[0].unit
				})
				this.onLoad()
			},
			changNewDataTime1(val) {
				let myDate = new Date(val)
				myDate.setTime(myDate.getTime() + 24 * 60 * 60 * 1000);
				this.newDataTime2 = dateFormat(new Date(myDate), 'yyyy-MM-dd')
			},
			changNewDataTime2(val) {
				let myDate = new Date(val)
				myDate.setTime(myDate.getTime() - 24 * 60 * 60 * 1000);
				this.newDataTime1 = dateFormat(new Date(myDate), 'yyyy-MM-dd')
			},
			changNewDataTime3(val) {
				val += "-01"
				let myDate = new Date(val)
				let str = dateFormat(new Date(myDate), 'yyyy-MM-dd')
				this.newDataTime4 = getNextMonth(str).slice(0, 7)

			},
			changNewDataTime4(val) {
				val += "-01"
				let myDate = new Date(val)
				let str = dateFormat(new Date(myDate), 'yyyy-MM-dd')
				this.newDataTime3 = getPreMonth(str).slice(0, 7)

			},
			/*** 初始化表单*/
			// initData() {
			//   // 树内容接口
			//   getDeptTree('2').then(res => {
			//     this.treeData = res.data.data
			//     this.$nextTick(function () {
			//       // 获取el-tree对象
			//       let elTreeDom = this.$refs.tree.$children[1]
			//       // 获取要设置的节点-第一个最下层节点,并设置默认选中
			//       let firstNode = this.getFirstNode(res.data.data)
			//       elTreeDom.setCurrentNode(firstNode)
			//       this.nodeClick(firstNode)
			//     })
			//   })
			// },
			getTimeProp() {
				let myDate = null;
				this.dateTime2 = dateFormat(new Date(), 'yyyy-MM-dd') // 默认显示的日期
				myDate = new Date(this.dateTime2)
				switch(this.propId) {
					case 1: //同比
						if(this.dateType == 2) {
							myDate.setTime(myDate.getTime() - 24 * 60 * 60 * 1000);
							this.dateTime = dateFormat(new Date(myDate), 'yyyy-MM-dd')
						}
						//月
						else if(this.dateType == 4) {
							this.dateTime = getPreMonth(this.dateTime2)
						}
						break;
					case 2: //环比
						if(this.dateType == 2) { //日
							this.dateTime = getPreMonth(this.dateTime2)
						} else if(this.dateType == 4) { //月
							this.dateTime2.slice(0, 7)
							let y = this.dateTime2.substring(4, 7)
							let x = (parseInt(this.dateTime2.substring(0, 4)) - 1) + y
							this.dateTime = x
						}
						break;
				}
			},
			changeTreeBox() {
				this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
				this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
			},
			// 搜索
			search() {
				for(var i = 0; i < this.geneList.length; i++) {
					if(this.gene == this.geneList[i].factorCode) {
						this.unit = this.geneList[i].unit
						break;
					}
				}
				this.onLoad()
			},
			/*** 树点击事件*/
			// async nodeClick(data) {
			//   if (data.nodeType != 2) {
			//     return false
			//   }
			//   this.nodeId = data.key
			//   this.deptInfoName = data.title
			//   this.deptInfoId = data.key
			//   await getFactorList(this.nodeId).then(res => {
			//     this.geneList = res.data.data;
			//     this.gene = this.geneList[0].factorCode;
			//     this.unit = this.geneList[0].unit
			//   })
			//   this.onLoad()
			// },
			/*** 获取第一个最下层节点*/
			// getFirstNode(tree, node = null) {
			//   tree.forEach(item => {
			//     if (!node) {
			//       if (item.children && item.children.length) {
			//         node = this.getFirstNode(item.children, node)
			//       } else {
			//         node = item
			//       }
			//     }
			//   })
			//   return node
			// },
			/**柱状图**/
			getBarInfo(time1, time2) {
				getBar(this.nodeId, time1, time2, this.gene, this.dateType).then(res => {
					this.barChartOptions = {
						title: {
							text: 'IAQI',
							left: 30,
							top: 30,
							textStyle: {
								fontSize: 14
							},
						},
						color: ['#3398DB'],
						tooltip: {
							trigger: 'axis',
							axisPointer: { // 坐标轴指示器，坐标轴触发有效
								type: 'cross' // 默认为直线，可选为：'line' | 'shadow'  cross十字准星指示器。其实是种简写，表示启用两个正交的轴的 axisPointer。
							},
							// formatter: (params) => {
							//   console.log('params', params)
							//   for (let i = 0; i < params.length; i++) {
							//     return params[i].name
							//   }
							// }
						},
						legend: {},
						grid: {
							left: '3%',
							right: '4%',
							bottom: '3%',
							containLabel: true
						},
						xAxis: [{
							type: 'category',
							data: [],
							axisTick: {
								alignWithLabel: true
							}
						}],
						yAxis: [{
								type: 'value',
								axisLabel: {
									formatter: '{value} ',
									color: '#333',
								},
							},

						],
						series: []
					}
					if(res.data.data.length > 0) {
						this.barChartOptions.xAxis[0].data = res.data.data[0].xarray;
					}

					res.data.data.map((item, ind) => {
						this.barChartOptions.series.push({
							data: item.yarray,
							type: 'bar',
							// name:`站点${ind+1}`
							name: item.time,
							// itemStyle: {
							//   color: ""
							// }
						})

					})
					let len = this.barChartOptions.series.length
					let colorlist = ['#4199f6', '#E67716']; //定义颜色
					if(len > 0) {
						for(var i = 0; i < len; i++) {
							this.barChartOptions.series[i]['itemStyle'] = {
								color: colorlist[i]
							}
						}
					}
				})
			},
			onLoad() {
				if(this.nodeId) {
					this.loading = true;
					let time1, time2
					if(this.dateType == 2 && this.propId == 2) {
						time1 = this.newDataTime1
						time2 = this.newDataTime2
					} else if(this.dateType == 4 && this.propId == 2) {
						time1 = this.newDataTime3
						time2 = this.newDataTime4
					} else if(this.dateType == 2 && this.propId == 1) {
						time2 = this.newDataTime5
						time1 = getPreYear(this.newDataTime5)
					} else if(this.dateType == 4 && this.propId == 1) {
						time1 = getPreYear2(this.newDataTime6)
						time2 = this.newDataTime6
					}
					getLine(this.nodeId, time1, time2, this.gene, this.dateType).then(res => {
						this.chartOptions = {
							tooltip: {
								trigger: 'axis',
								axisPointer: { // 坐标轴指示器，坐标轴触发有效
									type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
								},
							},
							legend: {},
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							xAxis: [{
								type: 'category',
								data: [],
								axisLabel: {
									interval: this.interval, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
									color: '#333'
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false
							}],
							yAxis: {
								type: 'value',
								axisLabel: {
									formatter: '{value} ' + this.unit,
									color: '#333',
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false,
								splitLine: {
									show: true,
									lineStyle: {
										color: '#374062',
										type: 'dashed' //设置背景为虚线
									}
								}
							},
							series: []
						}
						if(res.data.data.length > 0) {
							this.chartOptions.xAxis[0].data = res.data.data[0].xarray;
						}
						res.data.data.map((item, ind) => {
							this.chartOptions.series.push({
								data: item.yarray,
								type: 'line',
								smooth: 0.5,
								// name:`站点${ind+1}`
								name: item.time
							})
						})

					})
					this.getBarInfo(time1, time2)
				}
			}
		}
	};
</script>
<style lang="scss">
	.proportion {
		.el-card__body {
			height: calc(100% - 35px);
			.avue-crud {
				height: calc(100% - 155px);
			}
		}
	}
</style>
<style lang="scss" scoped>
	.map {
		width: 100%;
		height: 500px;
	}
	
	.box {
		height: 100%;
		margin-bottom: 0;
	}
	
	.search-left {
		display: flex;
		height: 33px;
		line-height: 33px;
	}
	
	.el-row {
		height: calc(100% - 20px);
	}
	
	.el-col {
		height: 100%;
		overflow: auto;
	}
	
	.search-tools {
		height: 49px;
		display: flex;
		justify-content: space-between;
		padding: 0 8px;
	}
	
	.search-right {
		display: flex;
	}
	
	.search-tabs {
		height: 33px;
		display: flex;
		align-items: center;
		margin-right: 40px;
	}
	
	.overlay {
		position: absolute;
		width: 200px;
		height: 100%;
		opacity: 0;
		display: flex;
		align-items: center;
		padding-left: 6px;
		.tree-tool {
			height: 34px;
			width: 18px;
			background: #fff;
			box-shadow: 2px 1px 4px #ccc;
			border-top-right-radius: 3px;
			border-bottom-right-radius: 3px;
			cursor: pointer;
			display: flex;
			padding: 6px 0;
			z-index: 9999;
			.tool-line {
				margin-left: 3px;
				height: 100%;
				border-left: 1px solid #ddd;
			}
		}
	}
	
	.overlay:hover {
		opacity: 1;
	}
</style>